import { Form, Input, Modal } from 'antd'
import PropTypes from 'prop-types'
import { findOneRole, createRole, updateRole } from '@/api/role'
import { useEffect } from 'react'

const RoleForm = (props) => {
  const [form] = Form.useForm()

  useEffect(() => {
    async function fetchData () {
      if (props.role_id) {
        const { data } = await findOneRole({
          id: props.role_id
        })

        form.setFieldsValue(data)
      }
    }
    fetchData()
  }, [props.role_id])

  const onOk = async () => {
    const values = await form.validateFields()
    if (props.role_id) {
      //更新
      await updateRole({
        id: props.role_id,
        ...values
      })
    } else {
      //新增
      await createRole(values)
    }
    props.onOk()
  }

  const isDetail = Boolean(props.title.includes('详情'))
  return (
    <Modal
      title={props.title}
      open={props.visible}
      maskClosable={false}
      footer={isDetail ? null : undefined}
      cancelText="取消"
      okText="确定"
      onCancel={props.onCancel}
      onOk={onOk}
    >
      <Form
        form={form}
        autoComplete="off"
        disabled={isDetail}
        labelCol={{ span: 4 }}
      >
        <Form.Item
          name="name"
          label="角色名称"
          rules={[
            {
              required: true,
              message: '角色名称'
            }
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="code"
          label="角色编码"
          rules={[
            {
              required: true,
              message: '角色编码'
            }
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item name="description" label="描述">
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  )
}

RoleForm.propTypes = {
  role_id: PropTypes.number,
  title: PropTypes.string.isRequired,
  visible: PropTypes.bool.isRequired,
  onCancel: PropTypes.func.isRequired,
  onOk: PropTypes.func.isRequired
}

export default RoleForm